import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'


Vue.use(VueRouter)

//封装一个判断当前模块是否有权限的方法
function hasUrl(url, next) {
  //首先要判断当前要请求的地址在不在数组中，如果在就next不在就跳首页
  let result = store.getters.getUser.menus_url.some(item => url === item)
  if (result) {
    next()
  } else {
    next("/home")
  }
}
export const IndexRoutes = [
  {
    path: "/home",
    component: () => import("../views/home.vue"),

  },
  {
    path: "/menu",
    component: () => import("../views/menu/menu.vue"),
    meta: {
      title: "菜单管理"
    },
    beforeEnter: (to, from, next) => {
      hasUrl("/menu", next)
    }

  },
  {
    path: "/role",
    component: () => import("../views/role/role.vue"),
    meta: {
      title: "角色管理"
    },
    beforeEnter: (to, from, next) => {
      hasUrl("/role", next)
    }
  },
  {
    path: "/user",
    component: () => import("../views/user/user.vue"),
    meta: {
      title: "管理员管理"
    },
    beforeEnter: (to, from, next) => {
      hasUrl("/user", next)
    }
  },
  {
    path: "/cate",
    component: () => import("../views/cate/cate"),
    meta: {
      title: "商品分类"
    },
    beforeEnter: (to, from, next) => {
      hasUrl("/cate", next)
    }
  },
  {
    
    path: "/specs",
    component: () => import("../views/specs/specs.vue"),
    meta: {
      title: "商品规格"
    },
    beforeEnter: (to, from, next) => {
      hasUrl("/specs", next)
    }
  },
  {
    
    path: "/manage",
    component: () => import("../views/manage/manage.vue"),
    meta: {
      title: "商品详情管理"
    },
    beforeEnter: (to, from, next) => {
      hasUrl("/manage", next)
    }
  },
  
  {
    
    path: "/member",
    component: () => import("../views/member/member.vue"),
    meta: {
      title: "会员列表"
    },
    beforeEnter: (to, from, next) => {
      hasUrl("/member", next)
    }
  },
  {
    
    path: "/banner",
    component: () => import("../views/banner/banner.vue"),
    meta: {
      title: "轮播图管理"
    },
    beforeEnter: (to, from, next) => {
      hasUrl("/banner", next)
    }
  },
  {
    
    path: "/seck",
    component: () => import("../views/seck/seck.vue"),
    meta: {
      title: "活动列表"
    },
    beforeEnter: (to, from, next) => {
      hasUrl("/seck", next)
    }
  },



]

const routes = [
  {
    path: "/login",
    component: () => import("../pages/login.vue")

  },
  {
    path: "/index",
    component: () => import("../pages/index.vue"),
    children: [
      ...IndexRoutes,
      {
        path: "",
        redirect: "/home"
      }
    ]

  },
  
  {
    path: "*",
    redirect: "/login"
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  // 封装判断全局登陆事件
  // 先判断用户的访问地址是否是登陆
  if (to.path == "/login") {
    next()
    return
  }
  //判断用户是否登陆
  if (store.getters.getUser) {
    next()
    return
  }
  //如果未登录 就强制跳转到登录
  next("/login")
})


export default router
